package com.mvp.shq.washer.ui.orderConfirm;

import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.jaeger.library.StatusBarUtil;
import com.mvp.shq.washer.R;
import com.mvp.shq.washer.adapter.PatternAdapter;
import com.mvp.shq.washer.base.BaseActivity;
import com.mvp.shq.washer.entity.OrderInfo;
import com.mvp.shq.washer.entity.User;
import com.mvp.shq.washer.entity.WxPayBean;
import com.mvp.shq.washer.entity.result.AliPay;
import com.mvp.shq.washer.entity.result.AuthResult;
import com.mvp.shq.washer.entity.Coupon;
import com.mvp.shq.washer.entity.OrderResponse;
import com.mvp.shq.washer.entity.PayResult;
import com.mvp.shq.washer.entity.Washer;
import com.mvp.shq.washer.entity.result.WasherInfoResult;
import com.mvp.shq.washer.entity.WasherPattern;
import com.mvp.shq.washer.entity.result.WxPayResult;
import com.mvp.shq.washer.rxbus.RxBus;
import com.mvp.shq.washer.rxbus.Subscribe;
import com.mvp.shq.washer.ui.coupon.CouponActivity;
import com.mvp.shq.washer.utils.DataDictionary;
import com.mvp.shq.washer.utils.EventCode;
import com.mvp.shq.washer.utils.JumpUtil;
import com.mvp.shq.washer.utils.RecyclerViewDivider;
import com.mvp.shq.washer.utils.SpUtil;
import com.mvp.shq.washer.utils.T;
import com.orhanobut.logger.Logger;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class OrderConfirmActivity extends BaseActivity<Presenter, Model> implements OrderConfirmConstract.View {

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.img_washer)
    ImageView imgWasher;
    @BindView(R.id.tv_washer_name)
    TextView tvWasherName;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_washer_no)
    TextView tvWasherNo;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.rb_wallet_pay)
    RadioButton rbWalletPay;
    @BindView(R.id.rb_wx_pay)
    RadioButton rbWxPay;
    @BindView(R.id.rb_alipay_pay)
    RadioButton rbAlipayPay;
    @BindView(R.id.tv_coupon_name)
    TextView tvCouponName;
    @BindView(R.id.tv_account_balance)
    TextView tvBalance;
    private RadioButton[] rbs = new RadioButton[4];
    private WasherInfoResult result;
    private int payType = 1;
    private List<WasherPattern> patterns;
    private int patternIndex = 0;
    private PatternAdapter adapter;
    private Coupon coupon;
    private String orderNo;
    private IWXAPI api;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        //Toast.makeText(PayDemoActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        paySuccess();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        //Toast.makeText(PayDemoActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                        T.show("支付失败");
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
//                        Toast.makeText(PayDemoActivity.this,
//                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
//                                .show();
                        T.show("授权成功");
                    } else {
                        // 其他状态值则为授权失败
//                        Toast.makeText(PayDemoActivity.this,
//                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();
                        T.show("授权失败");

                    }
                    break;
                }
                default:
                    break;
            }
        };
    };
    @Override
    public int getLayoutId() {
        return R.layout.activity_order_confirm;
    }

    @Override
    public void initView() {
        StatusBarUtil.setColor(this, ContextCompat.getColor(context, R.color.white), 0);
        title.setText("订单确认");
        String washerNo = getIntent().getExtras().getString("washerNo");
        showLoadingDialog(true);
        presenter.getWasherInfo(washerNo);
    }
    @Subscribe(code = EventCode.ON_PATTERN_CLICK)
    public void onPatternClick(Integer position){
        if (position == patternIndex){
            return;
        }
        patterns.get(patternIndex).setSelected(false);
        patterns.get(position).setSelected(true);
        patternIndex = position;
        adapter.notifyDataSetChanged();
    }


    @OnClick({R.id.all_rule,R.id.back, R.id.arl_coupon_pay, R.id.arl_wallet_pay, R.id.arl_wx_pay, R.id.arl_alipay_pay, R.id.btn_pay,R.id.rb_alipay_pay,
    R.id.rb_wallet_pay,R.id.rb_wx_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.all_rule:
                JumpUtil.toRule(context,"payRule");
                break;
            case R.id.back:
                finish();
                break;
            case R.id.arl_coupon_pay:
                JumpUtil.toCoupon(context, CouponActivity.CHOOSE);
                break;
            case R.id.arl_wallet_pay:
                setCheck(0);
                break;
            case R.id.rb_wallet_pay:
                setCheck(0);
                break;
            case R.id.arl_wx_pay:
                setCheck(1);
                break;
            case R.id.rb_wx_pay:
                setCheck(1);
                break;
            case R.id.arl_alipay_pay:
                setCheck(2);
                break;
            case R.id.rb_alipay_pay:
                setCheck(2);
                break;
            case R.id.btn_pay:
                OrderResponse response = new OrderResponse();
                response.setPatternId(patterns.get(patternIndex).getId());
                response.setTotalMoney(patterns.get(patternIndex).getPatternPrice());
                response.setWasherId(result.getWasher().getId());
                response.setUserId(SpUtil.getUser().getId());
                if (payType == 0){
                    //钱包支付
                    response.setPayType(2);
                }else if (payType == 1){
                    //微信支付
                    response.setPayType(0);
                    presenter.wxPay(response);
                    return;
                }else if (payType == 2){
                    //支付宝支付
                    response.setPayType(1);
                }else if (payType == 3){
                    //优惠券支付
                    response.setPayType(3);
                    response.setCouponId(coupon.getId());
                }
                showLoadingDialog(true);
                presenter.alipay(response);
                break;
        }
    }

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private void alipay(String orderInfo){
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(OrderConfirmActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    private void setCheck(int position){
        payType = position;
        for (int i=0;i<rbs.length;i++){
            rbs[i].setChecked(false);
        }
        if (payType != 3){
            rbs[position].setChecked(true);
            tvCouponName.setText("优惠券支付");
            coupon = null;
        }

    }

    @Subscribe(code = EventCode.CHOOSE_COUPON)
    public void couponBack(Coupon data){
        coupon = data;
        setCheck(3);
        tvCouponName.setText(coupon.getCouponName());
    }

    @Override
    public void getSignS(String orderStr) {

    }

    @Override
    public void getSignF(String msg) {

    }

    @Subscribe(code = EventCode.ORDER_PAY_SUCCESS)
    public void paySuccess(){
        T.show("支付成功");
        JumpUtil.toPaySuccess(context,orderNo);
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderNo(orderNo);
        orderInfo.setRestTime(patterns.get(patternIndex).getPatternTime());
        orderInfo.setPatternTime(patterns.get(patternIndex).getPatternTime());
        SpUtil.setOrder(orderInfo);
        RxBus.get().send(EventCode.GET_USER_INFO);
        RxBus.get().send(EventCode.GET_STATUS_ORDER);
        finish();
    }

    @Override
    public void alipayS(AliPay data) {
        orderNo = data.getOrderNo();
        switch (payType){
            case 0:
                //余额
                paySuccess();
                break;
            case 1:
                //微信
                break;
            case 2:
                //支付宝
                alipay(data.getAlipay().getBody());
                break;
            case 3:
                //优惠券
                paySuccess();
                break;
        }
    }

    @Override
    public void alipayF(String msg) {
        T.show(msg);
    }

    @Override
    public void wxPayS(WxPayResult result) {
        if (result == null){
            T.show("订单异常");
            return;
        }
        orderNo = result.getOrderNo();
        WxPayBean payBean = result.getWxpay();
        api = WXAPIFactory.createWXAPI(context,null);
        api.registerApp(payBean.getAppid());
        PayReq request = new PayReq();
        request.appId = payBean.getAppid();
        request.partnerId = payBean.getPartnerid();
        request.prepayId = payBean.getPrepayid();
        request.packageValue = payBean.getPackageX();
        request.nonceStr = payBean.getNoncestr();
        request.timeStamp = payBean.getTimestamp();
        request.sign = payBean.getSign();
        api.sendReq(request);
    }

    @Override
    public void getWasherInfoS(WasherInfoResult washerInfoResult) {
        result = washerInfoResult;
        User user = SpUtil.getUser();
        tvBalance.setText(user.getRechargeBalance().add(user.getGivenMoney())+"");
        Washer washer = result.getWasher();
        patterns = result.getWasherPatterns();
        if (patterns.size() > 0){
            patterns.get(0).setSelected(true);
            patternIndex = 0;
        }
        tvWasherName.setText(washer.getWasherBrand()+" "+washer.getWasherModel());
        tvWasherNo.setText("No."+washer.getWasherNo());
        tvAddress.setText(washer.getAddress()+washer.getDetailAddress());
        if(washer.getUpStatus() == null){
            tvStatus.setText("异常");
        }else if (washer.getUpStatus().equals(DataDictionary.WASHER_ONLINE)){
            if ("00".equals(washer.getStatus())){
                tvStatus.setText(" 空闲");
            }else if ("03".equals(washer.getStatus()) || "04".equals(washer.getStatus())){
                tvStatus.setText("运作中");
            }else if ("05".equals(washer.getStatus())){
                tvStatus.setText("自检中");
            }else if ("02".equals(washer.getStatus())){
                tvStatus.setText("消毒清洁中");
            }else if ("01".equals(washer.getStatus())){
                tvStatus.setText("预约中");
            }else{
                tvStatus.setText("异常");
            }
        }else if (washer.getUpStatus().equals(DataDictionary.WASHER_OUTLINE)){
            tvStatus.setText("离线");
        }

        rbs = new RadioButton[]{
                rbWalletPay,rbWxPay,rbAlipayPay
        };
        recyclerview.setLayoutManager(new GridLayoutManager(context,2, LinearLayoutManager.VERTICAL,false));
        RecyclerViewDivider divider1 = new RecyclerViewDivider(context,LinearLayoutManager.VERTICAL,28,getResources().getColor(R.color.white));
        recyclerview.addItemDecoration(divider1);
        adapter = new PatternAdapter(context,patterns);
        recyclerview.setAdapter(adapter);
        rbWxPay.setChecked(true);
        imageUtil.loadResImage(R.mipmap.washing_machine,imgWasher);
    }
}
